package abc.datasource;


import abc.config.DatasourceConfigure;
import abc.utils.JacksonUtil;
import abc.utils.StringUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
public class DynamicDataSourceProvider implements IDynamicDataSourceProvider {

    @Autowired
    DruidProperties druidProperties;

    @Resource
    DatasourceConfigure datasourceConfigure;

    @Override
    public Map<String, DataSource> loadDataSources() {
        Map<String, DataSource> ds = new HashMap<>(datasourceConfigure.getDatasource().entrySet().size());
        datasourceConfigure.getDatasource().entrySet().forEach(config-> {
            try {
                Map dsMap = JacksonUtil.convert(config.getValue(), Map.class);
                DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(dsMap);
                dataSource.setDriverClassName(config.getValue().getDriverClassName());
                dataSource.setUrl(config.getValue().getUrl());
                dataSource.setUsername(config.getValue().getUsername());
                dataSource.setPassword(config.getValue().getPassword());
                List<String> list = StringUtil.splitString2List(dataSource.getUrl(), "/");
                list = StringUtil.splitString2List(list.get(list.size()-1), "?");
                String dbname = list.get(0);
                config.getValue().setName(dbname);
                ds.put(config.getKey(), druidProperties.dataSource(dataSource));

                log.info(String.format("dataSource: %s, dbname: %s", config.getKey(), dbname));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });

        return ds;
    }

    @Override
    public String getPrimary() {
        return datasourceConfigure.getPrimary();
    }
}
